#!/bin/bash

# EKS Add-on Configuration Comparison Script
# This script compares EKS cluster configurations before and after add-on upgrades
# to ensure custom configurations are preserved

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Print functions
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_diff() {
    echo -e "${PURPLE}[DIFF]${NC} $1"
}

# Function to show usage
show_usage() {
    cat << EOF
Usage: $0 -b BEFORE_DIR -a AFTER_DIR [OPTIONS]

Required:
  -b, --before      Directory with configuration before upgrade
  -a, --after       Directory with configuration after upgrade

Optional:
  -o, --output      Output directory for comparison report (default: ./config-comparison-TIMESTAMP)
  -f, --format      Output format: text|json|html (default: text)
  -v, --verbose     Verbose output showing all comparisons
  -h, --help        Show this help message

Examples:
  $0 -b ./eks-config-before -a ./eks-config-after
  $0 -b ./eks-config-before -a ./eks-config-after -o ./comparison-report -f html
  $0 -b ./eks-config-before -a ./eks-config-after -v

Description:
This script compares EKS cluster configurations to identify changes after add-on upgrades:
- EKS managed add-on configurations and versions
- Kubernetes resource configurations (DaemonSets, Deployments, ConfigMaps)
- Custom Resource Definitions (CRDs) and custom resources
- IAM roles and policies (including IRSA)
- Security group rules and network configurations
- Node group and Auto Scaling Group settings

EOF
}

# Parse command line arguments
BEFORE_DIR=""
AFTER_DIR=""
OUTPUT_DIR=""
FORMAT="text"
VERBOSE=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -b|--before)
            BEFORE_DIR="$2"
            shift 2
            ;;
        -a|--after)
            AFTER_DIR="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT_DIR="$2"
            shift 2
            ;;
        -f|--format)
            FORMAT="$2"
            shift 2
            ;;
        -v|--verbose)
            VERBOSE=true
            shift
            ;;
        -h|--help)
            show_usage
            exit 0
            ;;
        *)
            echo "Unknown option $1"
            show_usage
            exit 1
            ;;
    esac
done

# Validate required parameters
if [[ -z "$BEFORE_DIR" || -z "$AFTER_DIR" ]]; then
    print_error "Both --before and --after directories are required"
    show_usage
    exit 1
fi

# Validate directories exist
if [[ ! -d "$BEFORE_DIR" ]]; then
    print_error "Before directory does not exist: $BEFORE_DIR"
    exit 1
fi

if [[ ! -d "$AFTER_DIR" ]]; then
    print_error "After directory does not exist: $AFTER_DIR"
    exit 1
fi

# Set default output directory
if [[ -z "$OUTPUT_DIR" ]]; then
    OUTPUT_DIR="./config-comparison-$(date +%Y%m%d-%H%M%S)"
fi

# Create output directory
mkdir -p "$OUTPUT_DIR"

print_info "Starting EKS configuration comparison"
print_info "Before: $BEFORE_DIR"
print_info "After: $AFTER_DIR"
print_info "Output: $OUTPUT_DIR"
print_info "Format: $FORMAT"

# Initialize comparison results
COMPARISON_RESULTS="$OUTPUT_DIR/comparison-results.json"
echo '{"timestamp":"'$(date -Iseconds)'","before_dir":"'$BEFORE_DIR'","after_dir":"'$AFTER_DIR'","comparisons":{}}' > "$COMPARISON_RESULTS"

# Function to add comparison result
add_comparison_result() {
    local category="$1"
    local item="$2"
    local status="$3"
    local details="$4"
    
    # Create temporary file with updated JSON
    jq --arg cat "$category" --arg item "$item" --arg status "$status" --arg details "$details" \
       '.comparisons[$cat] += [{item: $item, status: $status, details: $details}]' \
       "$COMPARISON_RESULTS" > "$COMPARISON_RESULTS.tmp" && mv "$COMPARISON_RESULTS.tmp" "$COMPARISON_RESULTS"
}

# Function to compare JSON files
compare_json_files() {
    local before_file="$1"
    local after_file="$2"
    local description="$3"
    local category="$4"
    
    if [[ ! -f "$before_file" && ! -f "$after_file" ]]; then
        return 0
    fi
    
    if [[ ! -f "$before_file" ]]; then
        print_warning "Missing before file: $description"
        add_comparison_result "$category" "$description" "added" "File added in after configuration"
        return 1
    fi
    
    if [[ ! -f "$after_file" ]]; then
        print_warning "Missing after file: $description"
        add_comparison_result "$category" "$description" "removed" "File removed in after configuration"
        return 1
    fi
    
    # Compare JSON content
    if jq -S . "$before_file" > /tmp/before_sorted.json 2>/dev/null && \
       jq -S . "$after_file" > /tmp/after_sorted.json 2>/dev/null; then
        
        if diff -q /tmp/before_sorted.json /tmp/after_sorted.json >/dev/null; then
            if [[ "$VERBOSE" == "true" ]]; then
                print_success "✓ No changes: $description"
            fi
            add_comparison_result "$category" "$description" "unchanged" "No changes detected"
            return 0
        else
            print_diff "△ Changes detected: $description"
            
            # Create detailed diff
            local diff_file="$OUTPUT_DIR/$(basename "$before_file" .json)-diff.txt"
            echo "=== Comparison: $description ===" > "$diff_file"
            echo "Before: $before_file" >> "$diff_file"
            echo "After: $after_file" >> "$diff_file"
            echo "" >> "$diff_file"
            diff -u /tmp/before_sorted.json /tmp/after_sorted.json >> "$diff_file" 2>/dev/null || true
            
            add_comparison_result "$category" "$description" "changed" "Changes detected - see $(basename "$diff_file")"
            return 1
        fi
    else
        print_warning "Failed to parse JSON: $description"
        add_comparison_result "$category" "$description" "error" "Failed to parse JSON files"
        return 1
    fi
}

# Function to compare YAML files
compare_yaml_files() {
    local before_file="$1"
    local after_file="$2"
    local description="$3"
    local category="$4"
    
    if [[ ! -f "$before_file" && ! -f "$after_file" ]]; then
        return 0
    fi
    
    if [[ ! -f "$before_file" ]]; then
        print_warning "Missing before file: $description"
        add_comparison_result "$category" "$description" "added" "File added in after configuration"
        return 1
    fi
    
    if [[ ! -f "$after_file" ]]; then
        print_warning "Missing after file: $description"
        add_comparison_result "$category" "$description" "removed" "File removed in after configuration"
        return 1
    fi
    
    # Compare YAML content (convert to JSON for consistent comparison)
    if yq eval -o=json '.' "$before_file" 2>/dev/null | jq -S . > /tmp/before_yaml.json && \
       yq eval -o=json '.' "$after_file" 2>/dev/null | jq -S . > /tmp/after_yaml.json; then
        
        if diff -q /tmp/before_yaml.json /tmp/after_yaml.json >/dev/null; then
            if [[ "$VERBOSE" == "true" ]]; then
                print_success "✓ No changes: $description"
            fi
            add_comparison_result "$category" "$description" "unchanged" "No changes detected"
            return 0
        else
            print_diff "△ Changes detected: $description"
            
            # Create detailed diff
            local diff_file="$OUTPUT_DIR/$(basename "$before_file" .yaml)-diff.txt"
            echo "=== Comparison: $description ===" > "$diff_file"
            echo "Before: $before_file" >> "$diff_file"
            echo "After: $after_file" >> "$diff_file"
            echo "" >> "$diff_file"
            diff -u /tmp/before_yaml.json /tmp/after_yaml.json >> "$diff_file" 2>/dev/null || true
            
            add_comparison_result "$category" "$description" "changed" "Changes detected - see $(basename "$diff_file")"
            return 1
        fi
    else
        # Fallback to text comparison if YAML parsing fails
        if diff -q "$before_file" "$after_file" >/dev/null; then
            if [[ "$VERBOSE" == "true" ]]; then
                print_success "✓ No changes: $description"
            fi
            add_comparison_result "$category" "$description" "unchanged" "No changes detected"
            return 0
        else
            print_diff "△ Changes detected: $description"
            
            local diff_file="$OUTPUT_DIR/$(basename "$before_file" .yaml)-diff.txt"
            echo "=== Comparison: $description ===" > "$diff_file"
            echo "Before: $before_file" >> "$diff_file"
            echo "After: $after_file" >> "$diff_file"
            echo "" >> "$diff_file"
            diff -u "$before_file" "$after_file" >> "$diff_file" 2>/dev/null || true
            
            add_comparison_result "$category" "$description" "changed" "Changes detected - see $(basename "$diff_file")"
            return 1
        fi
    fi
}

# Function to compare EKS managed add-ons
compare_eks_addons() {
    print_info "=== Comparing EKS Managed Add-ons ==="
    
    local before_addons="$BEFORE_DIR/cluster-addons.json"
    local after_addons="$AFTER_DIR/cluster-addons.json"
    
    # Compare add-on list
    compare_json_files "$before_addons" "$after_addons" "EKS Add-ons List" "eks_addons"
    
    # Compare individual add-ons
    if [[ -d "$BEFORE_DIR/addons" && -d "$AFTER_DIR/addons" ]]; then
        for addon_file in "$BEFORE_DIR/addons"/*.json; do
            if [[ -f "$addon_file" ]]; then
                local addon_name=$(basename "$addon_file")
                local after_addon="$AFTER_DIR/addons/$addon_name"
                compare_json_files "$addon_file" "$after_addon" "Add-on: $(basename "$addon_name" .json)" "eks_addons"
            fi
        done
        
        # Check for new add-ons in after directory
        for addon_file in "$AFTER_DIR/addons"/*.json; do
            if [[ -f "$addon_file" ]]; then
                local addon_name=$(basename "$addon_file")
                local before_addon="$BEFORE_DIR/addons/$addon_name"
                if [[ ! -f "$before_addon" ]]; then
                    print_warning "New add-on found: $(basename "$addon_name" .json)"
                    add_comparison_result "eks_addons" "Add-on: $(basename "$addon_name" .json)" "added" "New add-on added"
                fi
            fi
        done
    fi
    
    # Compare add-on configurations
    if [[ -d "$BEFORE_DIR/addon-configs" && -d "$AFTER_DIR/addon-configs" ]]; then
        for config_file in "$BEFORE_DIR/addon-configs"/*.json; do
            if [[ -f "$config_file" ]]; then
                local config_name=$(basename "$config_file")
                local after_config="$AFTER_DIR/addon-configs/$config_name"
                compare_json_files "$config_file" "$after_config" "Add-on Config: $(basename "$config_name" .json)" "addon_configs"
            fi
        done
    fi
}

# Function to compare Kubernetes add-on resources
compare_addon_k8s_resources() {
    print_info "=== Comparing Add-on Kubernetes Resources ==="
    
    if [[ -d "$BEFORE_DIR/addon-k8s-resources" && -d "$AFTER_DIR/addon-k8s-resources" ]]; then
        for resource_file in "$BEFORE_DIR/addon-k8s-resources"/*.yaml; do
            if [[ -f "$resource_file" ]]; then
                local resource_name=$(basename "$resource_file")
                local after_resource="$AFTER_DIR/addon-k8s-resources/$resource_name"
                compare_yaml_files "$resource_file" "$after_resource" "K8s Resource: $(basename "$resource_name" .yaml)" "k8s_resources"
            fi
        done
        
        # Check for new resources
        for resource_file in "$AFTER_DIR/addon-k8s-resources"/*.yaml; do
            if [[ -f "$resource_file" ]]; then
                local resource_name=$(basename "$resource_file")
                local before_resource="$BEFORE_DIR/addon-k8s-resources/$resource_name"
                if [[ ! -f "$before_resource" ]]; then
                    print_warning "New Kubernetes resource: $(basename "$resource_name" .yaml)"
                    add_comparison_result "k8s_resources" "K8s Resource: $(basename "$resource_name" .yaml)" "added" "New Kubernetes resource added"
                fi
            fi
        done
    elif [[ -d "$BEFORE_DIR/addon-k8s-resources" ]]; then
        print_warning "Add-on Kubernetes resources directory missing in after configuration"
        add_comparison_result "k8s_resources" "addon-k8s-resources directory" "removed" "Directory removed in after configuration"
    elif [[ -d "$AFTER_DIR/addon-k8s-resources" ]]; then
        print_warning "Add-on Kubernetes resources directory added in after configuration"
        add_comparison_result "k8s_resources" "addon-k8s-resources directory" "added" "Directory added in after configuration"
    fi
}

# Function to compare CRDs
compare_crds() {
    print_info "=== Comparing Custom Resource Definitions ==="
    
    if [[ -d "$BEFORE_DIR/crds" && -d "$AFTER_DIR/crds" ]]; then
        # Compare all CRDs file
        compare_yaml_files "$BEFORE_DIR/crds/all-crds.yaml" "$AFTER_DIR/crds/all-crds.yaml" "All CRDs" "crds"
        
        # Compare individual CRDs
        for crd_file in "$BEFORE_DIR/crds"/*.yaml; do
            if [[ -f "$crd_file" && "$(basename "$crd_file")" != "all-crds.yaml" ]]; then
                local crd_name=$(basename "$crd_file")
                local after_crd="$AFTER_DIR/crds/$crd_name"
                compare_yaml_files "$crd_file" "$after_crd" "CRD: $(basename "$crd_name" .yaml)" "crds"
            fi
        done
        
        # Check for new CRDs
        for crd_file in "$AFTER_DIR/crds"/*.yaml; do
            if [[ -f "$crd_file" && "$(basename "$crd_file")" != "all-crds.yaml" ]]; then
                local crd_name=$(basename "$crd_file")
                local before_crd="$BEFORE_DIR/crds/$crd_name"
                if [[ ! -f "$before_crd" ]]; then
                    print_warning "New CRD: $(basename "$crd_name" .yaml)"
                    add_comparison_result "crds" "CRD: $(basename "$crd_name" .yaml)" "added" "New CRD added"
                fi
            fi
        done
    fi
}

# Function to compare custom resources
compare_custom_resources() {
    print_info "=== Comparing Custom Resources ==="
    
    if [[ -d "$BEFORE_DIR/custom-resources" && -d "$AFTER_DIR/custom-resources" ]]; then
        for resource_file in "$BEFORE_DIR/custom-resources"/*.yaml; do
            if [[ -f "$resource_file" ]]; then
                local resource_name=$(basename "$resource_file")
                local after_resource="$AFTER_DIR/custom-resources/$resource_name"
                compare_yaml_files "$resource_file" "$after_resource" "Custom Resource: $(basename "$resource_name" .yaml)" "custom_resources"
            fi
        done
    fi
}

# Function to compare node groups
compare_node_groups() {
    print_info "=== Comparing Node Groups ==="
    
    # Compare managed node groups
    if [[ -d "$BEFORE_DIR/managed-nodegroups" && -d "$AFTER_DIR/managed-nodegroups" ]]; then
        for ng_file in "$BEFORE_DIR/managed-nodegroups"/*.json; do
            if [[ -f "$ng_file" ]]; then
                local ng_name=$(basename "$ng_file")
                local after_ng="$AFTER_DIR/managed-nodegroups/$ng_name"
                compare_json_files "$ng_file" "$after_ng" "Managed NodeGroup: $(basename "$ng_name" .json)" "node_groups"
            fi
        done
    fi
    
    # Compare Auto Scaling Groups
    if [[ -d "$BEFORE_DIR/asgs" && -d "$AFTER_DIR/asgs" ]]; then
        for asg_file in "$BEFORE_DIR/asgs"/*.json; do
            if [[ -f "$asg_file" ]]; then
                local asg_name=$(basename "$asg_file")
                local after_asg="$AFTER_DIR/asgs/$asg_name"
                compare_json_files "$asg_file" "$after_asg" "ASG: $(basename "$asg_name" .json)" "node_groups"
            fi
        done
    fi
}

# Function to compare IAM roles and policies
compare_iam() {
    print_info "=== Comparing IAM Roles and Policies ==="
    
    if [[ -d "$BEFORE_DIR/iam" && -d "$AFTER_DIR/iam" ]]; then
        for iam_file in "$BEFORE_DIR/iam"/*.json; do
            if [[ -f "$iam_file" ]]; then
                local iam_name=$(basename "$iam_file")
                local after_iam="$AFTER_DIR/iam/$iam_name"
                compare_json_files "$iam_file" "$after_iam" "IAM: $(basename "$iam_name" .json)" "iam"
            fi
        done
    fi
}

# Function to extract key configuration differences
extract_key_differences() {
    print_info "=== Extracting Key Configuration Differences ==="
    
    local key_diffs="$OUTPUT_DIR/key-differences.txt"
    echo "# Key Configuration Differences" > "$key_diffs"
    echo "Generated: $(date)" >> "$key_diffs"
    echo "" >> "$key_diffs"
    
    # Check for add-on version changes
    if [[ -f "$BEFORE_DIR/addons/vpc-cni.json" && -f "$AFTER_DIR/addons/vpc-cni.json" ]]; then
        local before_version=$(jq -r '.addon.addonVersion // "unknown"' "$BEFORE_DIR/addons/vpc-cni.json" 2>/dev/null)
        local after_version=$(jq -r '.addon.addonVersion // "unknown"' "$AFTER_DIR/addons/vpc-cni.json" 2>/dev/null)
        if [[ "$before_version" != "$after_version" ]]; then
            echo "## VPC-CNI Version Change" >> "$key_diffs"
            echo "Before: $before_version" >> "$key_diffs"
            echo "After: $after_version" >> "$key_diffs"
            echo "" >> "$key_diffs"
        fi
    fi
    
    # Check for environment variable changes in VPC-CNI DaemonSet
    if [[ -f "$BEFORE_DIR/addon-k8s-resources/vpc-cni-daemonset.yaml" && -f "$AFTER_DIR/addon-k8s-resources/vpc-cni-daemonset.yaml" ]]; then
        echo "## VPC-CNI DaemonSet Environment Variables" >> "$key_diffs"
        
        # Extract environment variables
        if command -v yq >/dev/null 2>&1; then
            yq eval '.spec.template.spec.containers[0].env[] | .name + "=" + .value' "$BEFORE_DIR/addon-k8s-resources/vpc-cni-daemonset.yaml" 2>/dev/null | sort > /tmp/before_env.txt
            yq eval '.spec.template.spec.containers[0].env[] | .name + "=" + .value' "$AFTER_DIR/addon-k8s-resources/vpc-cni-daemonset.yaml" 2>/dev/null | sort > /tmp/after_env.txt
            
            if ! diff -q /tmp/before_env.txt /tmp/after_env.txt >/dev/null 2>&1; then
                echo "Environment variable changes detected:" >> "$key_diffs"
                diff -u /tmp/before_env.txt /tmp/after_env.txt >> "$key_diffs" 2>/dev/null || true
            else
                echo "No environment variable changes" >> "$key_diffs"
            fi
        else
            echo "yq not available - cannot compare environment variables" >> "$key_diffs"
        fi
        echo "" >> "$key_diffs"
    fi
    
    print_success "Key differences extracted to: $key_diffs"
}

# Function to generate comparison report
generate_report() {
    print_info "=== Generating Comparison Report ==="
    
    local report_file="$OUTPUT_DIR/comparison-report.$FORMAT"
    
    case "$FORMAT" in
        "json")
            cp "$COMPARISON_RESULTS" "$report_file"
            ;;
        "html")
            generate_html_report "$report_file"
            ;;
        *)
            generate_text_report "$report_file"
            ;;
    esac
    
    print_success "Comparison report generated: $report_file"
}

# Function to generate text report
generate_text_report() {
    local report_file="$1"
    
    cat > "$report_file" << EOF
# EKS Configuration Comparison Report

**Generated:** $(date)
**Before Directory:** $BEFORE_DIR
**After Directory:** $AFTER_DIR

## Summary

EOF
    
    # Generate summary statistics
    local total_items=$(jq '[.comparisons[] | length] | add // 0' "$COMPARISON_RESULTS")
    local unchanged_items=$(jq '[.comparisons[][] | select(.status == "unchanged")] | length' "$COMPARISON_RESULTS")
    local changed_items=$(jq '[.comparisons[][] | select(.status == "changed")] | length' "$COMPARISON_RESULTS")
    local added_items=$(jq '[.comparisons[][] | select(.status == "added")] | length' "$COMPARISON_RESULTS")
    local removed_items=$(jq '[.comparisons[][] | select(.status == "removed")] | length' "$COMPARISON_RESULTS")
    
    cat >> "$report_file" << EOF
- **Total Items Compared:** $total_items
- **Unchanged:** $unchanged_items
- **Changed:** $changed_items
- **Added:** $added_items
- **Removed:** $removed_items

## Detailed Results

EOF
    
    # Generate detailed results by category
    jq -r '.comparisons | to_entries[] | "### " + .key + "\n" + (.value[] | "- **" + .item + "**: " + .status + " - " + .details) + "\n"' "$COMPARISON_RESULTS" >> "$report_file"
    
    echo "" >> "$report_file"
    echo "## Files Generated" >> "$report_file"
    echo "" >> "$report_file"
    find "$OUTPUT_DIR" -name "*.txt" -o -name "*.json" | while read -r file; do
        echo "- $(basename "$file")" >> "$report_file"
    done
}

# Function to generate HTML report
generate_html_report() {
    local report_file="$1"
    
    cat > "$report_file" << 'EOF'
<!DOCTYPE html>
<html>
<head>
    <title>EKS Configuration Comparison Report</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .header { background-color: #f0f0f0; padding: 10px; border-radius: 5px; }
        .summary { background-color: #e8f4fd; padding: 10px; border-radius: 5px; margin: 10px 0; }
        .category { margin: 20px 0; }
        .item { margin: 5px 0; padding: 5px; border-left: 3px solid #ccc; }
        .unchanged { border-left-color: #28a745; }
        .changed { border-left-color: #ffc107; }
        .added { border-left-color: #17a2b8; }
        .removed { border-left-color: #dc3545; }
        .error { border-left-color: #6c757d; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <div class="header">
        <h1>EKS Configuration Comparison Report</h1>
        <p><strong>Generated:</strong> $(date)</p>
        <p><strong>Before Directory:</strong> $BEFORE_DIR</p>
        <p><strong>After Directory:</strong> $AFTER_DIR</p>
    </div>
EOF
    
    # Add summary section
    local total_items=$(jq '[.comparisons[] | length] | add // 0' "$COMPARISON_RESULTS")
    local unchanged_items=$(jq '[.comparisons[][] | select(.status == "unchanged")] | length' "$COMPARISON_RESULTS")
    local changed_items=$(jq '[.comparisons[][] | select(.status == "changed")] | length' "$COMPARISON_RESULTS")
    local added_items=$(jq '[.comparisons[][] | select(.status == "added")] | length' "$COMPARISON_RESULTS")
    local removed_items=$(jq '[.comparisons[][] | select(.status == "removed")] | length' "$COMPARISON_RESULTS")
    
    cat >> "$report_file" << EOF
    <div class="summary">
        <h2>Summary</h2>
        <table>
            <tr><th>Status</th><th>Count</th></tr>
            <tr><td>Total Items</td><td>$total_items</td></tr>
            <tr><td>Unchanged</td><td>$unchanged_items</td></tr>
            <tr><td>Changed</td><td>$changed_items</td></tr>
            <tr><td>Added</td><td>$added_items</td></tr>
            <tr><td>Removed</td><td>$removed_items</td></tr>
        </table>
    </div>
    
    <h2>Detailed Results</h2>
EOF
    
    # Generate detailed results
    jq -r '.comparisons | to_entries[] | "<div class=\"category\"><h3>" + .key + "</h3>" + (.value[] | "<div class=\"item " + .status + "\"><strong>" + .item + "</strong>: " + .status + " - " + .details + "</div>") + "</div>"' "$COMPARISON_RESULTS" >> "$report_file"
    
    echo "</body></html>" >> "$report_file"
}

# Main execution
main() {
    print_info "Starting configuration comparison..."
    
    # Run comparisons
    compare_eks_addons
    compare_addon_k8s_resources
    compare_crds
    compare_custom_resources
    compare_node_groups
    compare_iam
    
    # Extract key differences
    extract_key_differences
    
    # Generate report
    generate_report
    
    # Summary
    print_success "Configuration comparison completed!"
    print_info "Results saved to: $OUTPUT_DIR"
    
    # Show summary statistics
    local total_items=$(jq '[.comparisons[] | length] | add // 0' "$COMPARISON_RESULTS")
    local changed_items=$(jq '[.comparisons[][] | select(.status == "changed")] | length' "$COMPARISON_RESULTS")
    local added_items=$(jq '[.comparisons[][] | select(.status == "added")] | length' "$COMPARISON_RESULTS")
    local removed_items=$(jq '[.comparisons[][] | select(.status == "removed")] | length' "$COMPARISON_RESULTS")
    
    echo ""
    print_info "=== Comparison Summary ==="
    print_info "Total items compared: $total_items"
    if [[ "$changed_items" -gt 0 ]]; then
        print_warning "Changed items: $changed_items"
    fi
    if [[ "$added_items" -gt 0 ]]; then
        print_info "Added items: $added_items"
    fi
    if [[ "$removed_items" -gt 0 ]]; then
        print_warning "Removed items: $removed_items"
    fi
    
    if [[ "$changed_items" -eq 0 && "$removed_items" -eq 0 ]]; then
        print_success "✓ No critical configuration changes detected!"
    else
        print_warning "⚠ Configuration changes detected - review the report for details"
    fi
}

# Check dependencies
check_dependencies() {
    local missing_deps=()
    
    if ! command -v jq >/dev/null 2>&1; then
        missing_deps+=("jq")
    fi
    
    if ! command -v diff >/dev/null 2>&1; then
        missing_deps+=("diff")
    fi
    
    if [[ ${#missing_deps[@]} -gt 0 ]]; then
        print_error "Missing required dependencies: ${missing_deps[*]}"
        print_info "Please install the missing dependencies and try again"
        exit 1
    fi
    
    # Optional dependencies
    if ! command -v yq >/dev/null 2>&1; then
        print_warning "yq not found - YAML comparison will use basic text diff"
    fi
}

# Run dependency check and main function
check_dependencies
main
